<template>
  <view class="ai-chat-container">
    <!-- 消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-into-view="scrollToView"
      :scroll-with-animation="true"
    >
      <view class="message-wrapper">
        <!-- 欢迎消息 -->
        <view v-if="messages.length === 0" class="welcome-message">
          <view class="welcome-icon">
            <u-icon name="chat" size="80" color="#5daf34"></u-icon>
          </view>
          <text class="welcome-title">AI智能助手</text>
          <text class="welcome-desc">我可以帮您解答关于找家教、学习辅导等问题</text>
        </view>

        <!-- 消息列表 -->
        <view 
          v-for="(message, index) in messages" 
          :key="message.id"
          :id="'msg-' + index"
          class="message-item"
          :class="message.role"
        >
           <view v-if="message.role === 'user'" class="user-message">
             <view class="message-content">
               <text class="message-text">{{ message.content }}</text>
             </view>
             <view class="message-avatar">
               <u-avatar :src="userAvatar" size="70rpx"></u-avatar>
             </view>
           </view>

          <view v-else class="ai-message">
            <view class="message-avatar">
              <view class="ai-avatar">
                <u-icon name="robot" size="24" color="white"></u-icon>
              </view>
            </view>
            <view class="message-content">
              <text class="message-text">{{ message.content }}</text>
              <view class="message-time">{{ formatTime(message.createdAt) }}</view>
            </view>
          </view>
        </view>

        <!-- 加载中提示 -->
        <view v-if="loading" class="message-item assistant">
          <view class="ai-message">
            <view class="message-avatar">
              <view class="ai-avatar">
                <u-icon name="robot" size="24" color="white"></u-icon>
              </view>
            </view>
            <view class="message-content loading">
              <view class="typing-indicator">
                <view class="dot"></view>
                <view class="dot"></view>
                <view class="dot"></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入框 -->
    <view class="input-container">
      <view class="input-wrapper">
        <view class="input-row">
          <textarea 
            v-model="inputMessage"
            class="message-input"
            placeholder="输入您的问题..."
            :auto-height="true"
            :maxlength="500"
            :disabled="loading"
            @confirm="handleEnter"
            @input="handleInput"
          />
          <view 
            class="send-button" 
            :class="{ active: canSend }"
            @click="sendMessage"
          >
            <u-icon name="arrow-right" size="28" :color="canSend ? 'white' : '#999'"></u-icon>
          </view>
        </view>
        <view class="input-footer">
          <text class="char-count">{{ inputMessage.length }}/500</text>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import { sendAiMessage, getMessages } from '@/api/ai'
import { getUserInfo } from '@/utils/auth'

export default {
  data() {
    return {
      conversationId: null,
      messages: [],
      inputMessage: '',
      loading: false,
      scrollToView: '',
      userAvatar: 'https://picsum.photos/100/100?random=user'
    }
  },

  computed: {
    canSend() {
      return this.inputMessage.trim().length > 0 && !this.loading
    }
  },

  onLoad(options) {
    // 如果有会话ID，加载历史消息
    if (options.conversationId) {
      this.conversationId = options.conversationId
      this.loadMessages()
    }
    
    // 获取用户头像
    const userInfo = getUserInfo()
    if (userInfo && userInfo.avatar) {
      this.userAvatar = userInfo.avatar
    }
  },

  methods: {
    // 加载历史消息
    async loadMessages() {
      try {
        const res = await getMessages(this.conversationId)
        if (res.code === 200) {
          this.messages = res.data
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        console.error('加载消息失败:', error)
      }
    },

    // 处理输入
    handleInput(e) {
      this.inputMessage = e.detail.value
    },

    // 处理Enter键
    handleEnter(e) {
      // 在小程序中，confirm事件相当于按下键盘的确认键
      this.sendMessage()
    },

    // 发送消息
    async sendMessage() {
      if (!this.canSend) {
        return
      }

      const message = this.inputMessage.trim()
      if (!message) {
        return
      }

      // 添加用户消息到列表
      const userMessage = {
        id: Date.now(),
        role: 'user',
        content: message,
        createdAt: new Date().toISOString()
      }
      this.messages.push(userMessage)

      // 清空输入框
      this.inputMessage = ''

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 显示加载状态
      this.loading = true

      try {
        const res = await sendAiMessage({
          conversationId: this.conversationId,
          message: message,
          newConversation: !this.conversationId
        })

        if (res.code === 200) {
          // 保存会话ID
          if (!this.conversationId) {
            this.conversationId = res.data.conversationId
          }

          // 添加AI回复到列表
          const aiMessage = {
            id: res.data.messageId,
            role: 'assistant',
            content: res.data.reply,
            createdAt: new Date().toISOString()
          }
          this.messages.push(aiMessage)

          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          uni.showToast({
            title: res.message || '发送失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 滚动到底部
    scrollToBottom() {
      if (this.messages.length > 0) {
        this.scrollToView = 'msg-' + (this.messages.length - 1)
      }
    },

    // 格式化时间
    formatTime(time) {
      const date = new Date(time)
      const now = new Date()
      const diff = now - date

      if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前'
      } else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      } else {
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours().toString().padStart(2, '0')
        const minute = date.getMinutes().toString().padStart(2, '0')
        return `${month}月${day}日 ${hour}:${minute}`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
}

.message-list {
  flex: 1;
  overflow-y: auto;
}

.message-wrapper {
  padding: 30rpx 30rpx 20rpx 30rpx;
  min-height: 100%;
  padding-bottom: 40rpx;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .welcome-icon {
    width: 160rpx;
    height: 160rpx;
    background: linear-gradient(135deg, #5daf34, #7cb342);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40rpx;
    box-shadow: 0 8rpx 32rpx rgba(93, 175, 52, 0.3);
  }
  
  .welcome-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .welcome-desc {
    font-size: 28rpx;
    color: #999;
    text-align: center;
    line-height: 1.6;
  }
}

.message-item {
  margin-bottom: 30rpx;
  
  &.user {
    .user-message {
      display: flex;
      justify-content: flex-end;
      align-items: flex-start;
      
      .message-content {
        max-width: 70%;
        background: linear-gradient(135deg, #5daf34, #7cb342);
        padding: 20rpx 24rpx;
        border-radius: 20rpx 20rpx 4rpx 20rpx;
        margin-right: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(93, 175, 52, 0.2);
        
        .message-text {
          font-size: 28rpx;
          color: white;
          line-height: 1.6;
          word-break: break-word;
        }
      }
      
      .message-avatar {
        flex-shrink: 0;
      }
    }
  }
  
  &.assistant {
    .ai-message {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      
       .message-avatar {
         flex-shrink: 0;
         margin-right: 16rpx;
         
         .ai-avatar {
           width: 70rpx;
           height: 70rpx;
           background: linear-gradient(135deg, #667eea, #764ba2);
           border-radius: 50%;
           display: flex;
           align-items: center;
           justify-content: center;
           box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
         }
       }
      
      .message-content {
        max-width: 70%;
        background: white;
        padding: 20rpx 24rpx;
        border-radius: 20rpx 20rpx 20rpx 4rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
        
        &.loading {
          padding: 30rpx;
        }
        
        .message-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.8;
          word-break: break-word;
        }
        
        .message-time {
          margin-top: 12rpx;
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  .dot {
    width: 12rpx;
    height: 12rpx;
    background: #5daf34;
    border-radius: 50%;
    animation: typing 1.4s infinite;
    
    &:nth-child(1) {
      animation-delay: 0s;
    }
    
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}

.input-container {
  background: white;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.input-wrapper {
  padding: 20rpx 30rpx;
}

.input-row {
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
}

.message-input {
  flex: 1;
  min-height: 80rpx;
  max-height: 200rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  line-height: 1.6;
  background: #f8f9fa;
  border-radius: 24rpx;
  border: 2rpx solid #e0e0e0;
  box-sizing: border-box;
  
  &:focus {
    border-color: #5daf34;
    background: #ffffff;
  }
}

.send-button {
  width: 80rpx;
  height: 80rpx;
  flex-shrink: 0;
  background: #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  margin-bottom: 0rpx;
  
  &.active {
    background: linear-gradient(135deg, #5daf34, #7cb342);
    box-shadow: 0 4rpx 16rpx rgba(93, 175, 52, 0.3);
    
    &:active {
      transform: scale(0.92);
    }
  }
}

.input-footer {
  margin-top: 12rpx;
  text-align: right;
}

.char-count {
  font-size: 22rpx;
  color: #999;
}

</style>


